package com.bdqn.zhang.dao;

import com.bdqn.zhang.entity.SysUser;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import java.util.List;

public class SysUserDaoImpl extends HibernateDaoSupport implements SysUserDao{

    @Override
    public void addSysUser(SysUser sysUser) {
        this.getHibernateTemplate().save(sysUser);
    }

    @Override
    public SysUser findUser(SysUser sysUser) {
        List<SysUser> userList = (List<SysUser>)this.getHibernateTemplate().findByValueBean("from SysUser u where u.name=:name and u.password=:password",sysUser);
        if(userList.size() > 0 && userList != null){
            return userList.get(0);
        } else {
            return null;
        }
    }

    /*@Override
    public List<SysUser> findAllUser() {
        List<SysUser> userList = (List<SysUser>)this.getHibernateTemplate().find("from SysUser");
        if(userList.size() > 0 && userList != null){
            return userList;
        } else {
            return null;
        }
    }*/

    @Override
    public List<SysUser> findAllUser(final Integer page,final Integer limit) {
        return this.getHibernateTemplate().execute(
                new HibernateCallback<List<SysUser>>() {
                    @Override
                    public List<SysUser> doInHibernate(Session session) throws HibernateException {
                        return  session.createQuery("from SysUser order by id asc").setFirstResult((page-1)*limit).setMaxResults(limit).list();
                    }
                });

        /*List<SysUser> userList = (List<SysUser>)this.getHibernateTemplate().find("from SysUser");
        if(userList.size() > 0 && userList != null){
            return userList;
        } else {
            return null;
        }*/
    }

    @Override
    public Long getUserCount() {
        Long count = (Long)this.getHibernateTemplate().iterate("select count(1) from SysUser").next();
        return count;
    }
}
